using System.Collections.Concurrent;
using LiteDB;

namespace FileTransferDesktop.Services
{
    public class UploadRecord
    {
        [BsonId] // 主键，自动生成 ObjectId
        public ObjectId? Id { get; set; }

        public string FileName { get; set; } = "";
        public string FilePath { get; set; } = "";
        public DateTime UploadTime { get; set; }
        public string ShareCode { get; set; } = "";
        public string Status { get; set; } = "";
        public string Message { get; set; } = "";
        public string EditToken { get; set; } = ""; // 编辑token，用于修改消息
    }

    public class DownloadRecord
    {
        [BsonId] // 主键
        public ObjectId? Id { get; set; }

        public string FileName { get; set; } = "";
        public string FilePath { get; set; } = "";
        public DateTime DownloadTime { get; set; } = DateTime.Now;
        public string FileSize { get; set; } = ""; // 字节数
        public string Status { get; set; } = "已下载";
        public string SourceUrl { get; set; } = "";
        public string Message { get; set; } = "";
    }

    /// <summary>
    /// 用户登录会话信息模型
    /// </summary>
    public class UserSession
    {
        [BsonId] // 主键
        public string SessionId { get; set; } = "";

        /// <summary>
        /// 用户基本信息
        /// </summary>
        public UserInfo User { get; set; } = new();

        /// <summary>
        /// 认证令牌
        /// </summary>
        public string Token { get; set; } = "";

        /// <summary>
        /// 令牌类型 (通常是 "Bearer")
        /// </summary>
        public string TokenType { get; set; } = "Bearer";

        /// <summary>
        /// 登录时间
        /// </summary>
        public DateTime LoginTime { get; set; } = DateTime.Now;

        /// <summary>
        /// 最后活动时间
        /// </summary>
        public DateTime LastActivityTime { get; set; } = DateTime.Now;

        /// <summary>
        /// 令牌过期时间 (可选，从JWT中解析或设置默认值)
        /// </summary>
        public DateTime? ExpiryTime { get; set; }

        /// <summary>
        /// 是否记住登录状态
        /// </summary>
        public bool RememberMe { get; set; } = false;

        /// <summary>
        /// 登录设备信息
        /// </summary>
        public string DeviceInfo { get; set; } = "";

        /// <summary>
        /// 会话状态
        /// </summary>
        public SessionStatus Status { get; set; } = SessionStatus.Active;

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedAt { get; set; } = DateTime.Now;

        /// <summary>
        /// 更新时间
        /// </summary>
        public DateTime UpdatedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 用户基本信息
    /// </summary>
    public class UserInfo
    {
        public long Id { get; set; }
        public string Username { get; set; } = "";
        public string Email { get; set; } = "";
        public string DisplayName { get; set; } = "";
        public string Role { get; set; } = "";
        public bool Enabled { get; set; } = true;
        public DateTime CreatedAt { get; set; }
        public DateTime LastLogin { get; set; }
        public string AvatarUrl { get; set; } = "";
    }

    /// <summary>
    /// 会话状态枚举
    /// </summary>
    public enum SessionStatus
    {
        /// <summary>
        /// 活跃状态
        /// </summary>
        Active,

        /// <summary>
        /// 已过期
        /// </summary>
        Expired,

        /// <summary>
        /// 已注销
        /// </summary>
        LoggedOut,

        /// <summary>
        /// 被撤销
        /// </summary>
        Revoked,
    }

    /// <summary>
    /// 最后登录用户信息
    /// </summary>
    public class LastLoginInfo
    {
        [BsonId] // 主键
        public string Key { get; set; } = "last_login";
        public string Username { get; set; } = "";
        public string DisplayName { get; set; } = "";
        public string AvatarUrl { get; set; } = "";
        public DateTime LastLoginTime { get; set; } = DateTime.Now;
        public DateTime CreatedAt { get; set; } = DateTime.Now;
        public DateTime UpdatedAt { get; set; } = DateTime.Now;
    }

    public class RecycleRecord
    {
        [BsonId]
        public ObjectId Id { get; set; } = ObjectId.NewObjectId();

        public string Type { get; set; } = ""; // "upload" 或 "download"

        public string FileName { get; set; } = "";

        public string FilePath { get; set; } = "";

        public string Message { get; set; } = "";

        public DateTime OriginalTime { get; set; } // 原始上传/下载时间

        public DateTime DeletedAt { get; set; } = DateTime.Now;

        public string ShareCode { get; set; } = ""; // 如果有
    }

    /// <summary>
    /// 优化的本地数据库服务，支持连接池和多线程安全操作
    /// </summary>
    public class LocalDbService
    {
        private const string DbPath = "UserData.db";
        private const string CurrentSessionKey = "current_session";

        // 线程安全的数据库连接池
        private static readonly Lock Lock = new();
        private static LiteDatabase? _database;
        private static readonly Lock InstanceLock = new();
        private static LocalDbService? _instance;

        // 线程安全的操作锁，防止并发修改同一资源
        private static readonly ConcurrentDictionary<string, SemaphoreSlim> CollectionLocks = new();

        // 获取单例实例
        public static LocalDbService Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (InstanceLock)
                    {
                        _instance ??= new LocalDbService();
                    }
                }
                return _instance;
            }
        }

        // 私有构造函数
        private LocalDbService()
        {
            InitializeDatabase();
        }

        // 初始化数据库连接
        private static void InitializeDatabase()
        {
            if (_database == null)
            {
                lock (Lock)
                {
                    if (_database == null)
                    {
                        var connectionString = $"Filename={DbPath};Connection=shared;";
                        _database = new LiteDatabase(connectionString);
                    }
                }
            }
        }

        // 获取数据库实例
        private static LiteDatabase GetDatabase()
        {
            if (_database == null)
            {
                InitializeDatabase();
            }
            return _database!;
        }

        // 获取集合锁
        private static SemaphoreSlim GetCollectionLock(string collectionName)
        {
            return CollectionLocks.GetOrAdd(collectionName, _ => new SemaphoreSlim(1, 1));
        } // 通用数据库操作方法

        public static T ExecuteDbOperation<T>(Func<LiteDatabase, T> operation)
        {
            lock (Lock) // 确保数据库操作的原子性
            {
                try
                {
                    var db = GetDatabase();
                    return operation(db);
                }
                catch (Exception ex)
                {
                    // 如果数据库连接出现问题，重新初始化
                    if (ex is LiteException || ex is ObjectDisposedException)
                    {
                        _database?.Dispose();
                        _database = null;
                        InitializeDatabase();
                        var db = GetDatabase();
                        return operation(db);
                    }
                    throw;
                }
            }
        }

        // 异步数据库操作方法
        private static async Task<T> ExecuteDbOperationAsync<T>(
            string collectionName,
            Func<LiteDatabase, T> operation
        )
        {
            var collectionLock = GetCollectionLock(collectionName);
            await collectionLock.WaitAsync();
            try
            {
                return await Task.Run(() => ExecuteDbOperation(operation));
            }
            finally
            {
                collectionLock.Release();
            }
        }

        // 无返回值的异步操作
        private static async Task ExecuteDbOperationAsync(
            string collectionName,
            Action<LiteDatabase> operation
        )
        {
            await ExecuteDbOperationAsync(
                collectionName,
                db =>
                {
                    operation(db);
                    return true;
                }
            );
        }

        // 释放资源
        public static void Dispose()
        {
            lock (Lock)
            {
                _database?.Dispose();
                _database = null;
            }

            foreach (var lockPair in CollectionLocks)
            {
                lockPair.Value.Dispose();
            }
            CollectionLocks.Clear();

            _instance = null;
        }

        #region Upload Records
        public static void SaveUpload(UploadRecord record)
        {
            ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<UploadRecord>("uploads");
                col.Insert(record);
                return true;
            });
        }

        public static async Task SaveUploadAsync(UploadRecord record)
        {
            await ExecuteDbOperationAsync(
                "uploads",
                db =>
                {
                    var col = db.GetCollection<UploadRecord>("uploads");
                    col.Insert(record);
                }
            );
        }

        public static IEnumerable<UploadRecord> GetAllUploads()
        {
            return ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<UploadRecord>("uploads");
                return col.FindAll().ToList();
            });
        }

        public static async Task<IEnumerable<UploadRecord>> GetAllUploadsAsync()
        {
            return await ExecuteDbOperationAsync(
                "uploads",
                db =>
                {
                    var col = db.GetCollection<UploadRecord>("uploads");
                    return col.FindAll().ToList();
                }
            );
        }

        public static void DeleteUpload(ObjectId id)
        {
            ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<UploadRecord>("uploads");
                var record = col.FindById(id);
                if (record == null)
                    return true;
                AddToRecycleBin(
                    "upload",
                    record.FileName,
                    record.FilePath,
                    record.Message,
                    record.UploadTime,
                    record.ShareCode
                );
                col.Delete(id);
                return true;
            });
        }

        public static async Task<bool> DeleteUploadAsync(ObjectId id)
        {
            return await ExecuteDbOperationAsync(
                "uploads",
                db =>
                {
                    var col = db.GetCollection<UploadRecord>("uploads");
                    return col.Delete(id);
                }
            );
        }

        public static ObjectId? GetUploadIdByTime(DateTime uploadTime)
        {
            return ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<UploadRecord>("uploads");
                var record = col.FindOne(r => r.UploadTime == uploadTime);
                return record?.Id;
            });
        }

        public static async Task<ObjectId?> GetUploadIdByTimeAsync(DateTime uploadTime)
        {
            return await ExecuteDbOperationAsync(
                "uploads",
                db =>
                {
                    var col = db.GetCollection<UploadRecord>("uploads");
                    var record = col.FindOne(r => r.UploadTime == uploadTime);
                    return record?.Id;
                }
            );
        }

        // 更新上传记录的消息
        public static void UpdateUploadMessage(ObjectId id, string message)
        {
            ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<UploadRecord>("uploads");
                var record = col.FindById(id);
                if (record != null)
                {
                    record.Message = message;
                    col.Update(record);
                }
                return true;
            });
        }

        public static async Task UpdateUploadMessageAsync(ObjectId id, string message)
        {
            await ExecuteDbOperationAsync(
                "uploads",
                db =>
                {
                    var col = db.GetCollection<UploadRecord>("uploads");
                    var record = col.FindById(id);
                    if (record != null)
                    {
                        record.Message = message;
                        col.Update(record);
                    }
                }
            );
        }
        #endregion

        #region Download Records
        public static void SaveDownload(DownloadRecord record)
        {
            ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<DownloadRecord>("downloads");
                col.Insert(record);
                return true;
            });
        }

        public static async Task SaveDownloadAsync(DownloadRecord record)
        {
            await ExecuteDbOperationAsync(
                "downloads",
                db =>
                {
                    var col = db.GetCollection<DownloadRecord>("downloads");
                    col.Insert(record);
                }
            );
        }

        public static IEnumerable<DownloadRecord> GetAllDownloads()
        {
            return ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<DownloadRecord>("downloads");
                return col.FindAll().ToList();
            });
        }

        public static async Task<IEnumerable<DownloadRecord>> GetAllDownloadsAsync()
        {
            return await ExecuteDbOperationAsync(
                "downloads",
                db =>
                {
                    var col = db.GetCollection<DownloadRecord>("downloads");
                    return col.FindAll().ToList();
                }
            );
        }

        public static void DeleteDownload(ObjectId id)
        {
            ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<DownloadRecord>("downloads");
                var record = col.FindById(id);
                if (record == null)
                    return true;
                AddToRecycleBin(
                    "download",
                    record.FileName,
                    record.FilePath,
                    record.Message,
                    record.DownloadTime
                );
                col.Delete(id);
                return true;
            });
        }

        public static async Task<bool> DeleteDownloadAsync(ObjectId id)
        {
            return await ExecuteDbOperationAsync(
                "downloads",
                db =>
                {
                    var col = db.GetCollection<DownloadRecord>("downloads");
                    return col.Delete(id);
                }
            );
        }

        public static ObjectId? GetDownloadIdByTime(DateTime downloadTime)
        {
            return ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<DownloadRecord>("downloads");
                var record = col.FindOne(r => r.DownloadTime == downloadTime);
                return record?.Id;
            });
        }

        public static async Task<ObjectId?> GetDownloadIdByTimeAsync(DateTime downloadTime)
        {
            return await ExecuteDbOperationAsync(
                "downloads",
                db =>
                {
                    var col = db.GetCollection<DownloadRecord>("downloads");
                    var record = col.FindOne(r => r.DownloadTime == downloadTime);
                    return record?.Id;
                }
            );
        }
        #endregion

        #region User Session Management
        /// <summary>
        /// 保存用户会话信息
        /// </summary>
        /// <param name="session">用户会话信息</param>
        public static void SaveUserSession(UserSession session)
        {
            ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<UserSession>("user_sessions");

                // 更新时间戳
                session.UpdatedAt = DateTime.Now;

                // 先删除现有的活跃会话（确保只有一个活跃会话）
                ClearCurrentSession();

                // 保存新会话
                col.Insert(session);

                // 设置为当前会话 - 使用简单的配置表
                var configCol = db.GetCollection<BsonDocument>("config");
                configCol.Upsert(
                    new BsonDocument { ["_id"] = CurrentSessionKey, ["value"] = session.SessionId }
                );

                return true;
            });
        }

        /// <summary>
        /// 异步保存用户会话信息
        /// </summary>
        /// <param name="session">用户会话信息</param>
        public static async Task SaveUserSessionAsync(UserSession session)
        {
            await ExecuteDbOperationAsync(
                "user_sessions",
                db =>
                {
                    var col = db.GetCollection<UserSession>("user_sessions");

                    // 更新时间戳
                    session.UpdatedAt = DateTime.Now;

                    // 先删除现有的活跃会话（确保只有一个活跃会话）
                    ClearCurrentSessionInternal(db);

                    // 保存新会话
                    col.Insert(session);

                    // 设置为当前会话 - 使用简单的配置表
                    var configCol = db.GetCollection<BsonDocument>("config");
                    configCol.Upsert(
                        new BsonDocument
                        {
                            ["_id"] = CurrentSessionKey,
                            ["value"] = session.SessionId,
                        }
                    );
                }
            );
        }

        /// <summary>
        /// 获取当前用户会话
        /// </summary>
        /// <returns>当前用户会话信息，如果不存在则返回null</returns>
        public static UserSession? GetCurrentUserSession()
        {
            try
            {
                return ExecuteDbOperation(db =>
                {
                    var configCol = db.GetCollection<BsonDocument>("config");
                    var sessionDoc = configCol.FindById(CurrentSessionKey);

                    if (sessionDoc == null || !sessionDoc.ContainsKey("value"))
                        return null;

                    var sessionId = sessionDoc["value"].AsString;
                    if (string.IsNullOrEmpty(sessionId))
                        return null;

                    var col = db.GetCollection<UserSession>("user_sessions");
                    var session = col.FindOne(s =>
                        s.SessionId == sessionId && s.Status == SessionStatus.Active
                    );

                    if (session != null)
                    {
                        // 更新最后活动时间
                        session.LastActivityTime = DateTime.Now;
                        session.UpdatedAt = DateTime.Now;
                        col.Update(session);
                    }

                    return session;
                });
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 异步获取当前用户会话
        /// </summary>
        /// <returns>当前用户会话信息，如果不存在则返回null</returns>
        public static async Task<UserSession?> GetCurrentUserSessionAsync()
        {
            try
            {
                return await ExecuteDbOperationAsync(
                    "user_sessions",
                    db =>
                    {
                        var configCol = db.GetCollection<BsonDocument>("config");
                        var sessionDoc = configCol.FindById(CurrentSessionKey);

                        if (sessionDoc == null || !sessionDoc.ContainsKey("value"))
                            return null;

                        var sessionId = sessionDoc["value"].AsString;
                        if (string.IsNullOrEmpty(sessionId))
                            return null;

                        var col = db.GetCollection<UserSession>("user_sessions");
                        var session = col.FindOne(s =>
                            s.SessionId == sessionId && s.Status == SessionStatus.Active
                        );

                        if (session != null)
                        {
                            // 更新最后活动时间
                            session.LastActivityTime = DateTime.Now;
                            session.UpdatedAt = DateTime.Now;
                            col.Update(session);
                        }

                        return session;
                    }
                );
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 更新用户会话信息
        /// </summary>
        /// <param name="session">要更新的会话信息</param>
        public static void UpdateUserSession(UserSession session)
        {
            ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<UserSession>("user_sessions");
                session.UpdatedAt = DateTime.Now;
                return col.Update(session);
            });
        }

        /// <summary>
        /// 异步更新用户会话信息
        /// </summary>
        /// <param name="session">要更新的会话信息</param>
        public static async Task<bool> UpdateUserSessionAsync(UserSession session)
        {
            return await ExecuteDbOperationAsync(
                "user_sessions",
                db =>
                {
                    var col = db.GetCollection<UserSession>("user_sessions");
                    session.UpdatedAt = DateTime.Now;
                    return col.Update(session);
                }
            );
        }

        /// <summary>
        /// 清除当前会话
        /// </summary>
        public static void ClearCurrentSession()
        {
            try
            {
                ExecuteDbOperation(db =>
                {
                    ClearCurrentSessionInternal(db);
                    return true;
                });
            }
            catch (Exception)
            {
                // 忽略错误，确保清理操作不会失败
            }
        }

        /// <summary>
        /// 异步清除当前会话
        /// </summary>
        public static async Task ClearCurrentSessionAsync()
        {
            try
            {
                await ExecuteDbOperationAsync(
                    "user_sessions",
                    db =>
                    {
                        ClearCurrentSessionInternal(db);
                    }
                );
            }
            catch (Exception)
            {
                // 忽略错误，确保清理操作不会失败
            }
        }

        /// <summary>
        /// 内部清除当前会话方法
        /// </summary>
        private static void ClearCurrentSessionInternal(LiteDatabase db)
        {
            var configCol = db.GetCollection<BsonDocument>("config");
            var sessionDoc = configCol.FindById(CurrentSessionKey);

            if (sessionDoc != null && sessionDoc.ContainsKey("value"))
            {
                var sessionId = sessionDoc["value"].AsString;
                if (!string.IsNullOrEmpty(sessionId))
                {
                    var col = db.GetCollection<UserSession>("user_sessions");
                    var session = col.FindOne(s => s.SessionId == sessionId);

                    if (session != null)
                    {
                        session.Status = SessionStatus.LoggedOut;
                        session.UpdatedAt = DateTime.Now;
                        col.Update(session);
                    }
                }
            }

            // 清除当前会话标记
            configCol.Delete(CurrentSessionKey);
        }

        /// <summary>
        /// 清理过期的会话
        /// </summary>
        public static void CleanupExpiredSessions()
        {
            try
            {
                ExecuteDbOperation(db =>
                {
                    var col = db.GetCollection<UserSession>("user_sessions");

                    var expiredSessions = col.Find(s =>
                        s.ExpiryTime.HasValue
                        && s.ExpiryTime.Value <= DateTime.Now
                        && s.Status == SessionStatus.Active
                    );

                    foreach (var session in expiredSessions)
                    {
                        session.Status = SessionStatus.Expired;
                        session.UpdatedAt = DateTime.Now;
                        col.Update(session);
                    }

                    return true;
                });
            }
            catch (Exception)
            {
                // 忽略清理错误
            }
        }

        /// <summary>
        /// 异步清理过期的会话
        /// </summary>
        public static async Task CleanupExpiredSessionsAsync()
        {
            try
            {
                await ExecuteDbOperationAsync(
                    "user_sessions",
                    db =>
                    {
                        var col = db.GetCollection<UserSession>("user_sessions");

                        var expiredSessions = col.Find(s =>
                            s.ExpiryTime.HasValue
                            && s.ExpiryTime.Value <= DateTime.Now
                            && s.Status == SessionStatus.Active
                        );

                        foreach (var session in expiredSessions)
                        {
                            session.Status = SessionStatus.Expired;
                            session.UpdatedAt = DateTime.Now;
                            col.Update(session);
                        }
                    }
                );
            }
            catch (Exception)
            {
                // 忽略清理错误
            }
        }

        /// <summary>
        /// 获取用户的所有会话记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户的会话记录列表</returns>
        public static IEnumerable<UserSession> GetUserSessions(long userId)
        {
            try
            {
                return ExecuteDbOperation(db =>
                {
                    var col = db.GetCollection<UserSession>("user_sessions");
                    return col.Find(s => s.User.Id == userId)
                        .OrderByDescending(s => s.CreatedAt)
                        .ToList();
                });
            }
            catch (Exception)
            {
                return (List<UserSession>)[];
            }
        }

        /// <summary>
        /// 异步获取用户的所有会话记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户的会话记录列表</returns>
        public static async Task<IEnumerable<UserSession>> GetUserSessionsAsync(long userId)
        {
            try
            {
                return await ExecuteDbOperationAsync(
                    "user_sessions",
                    db =>
                    {
                        var col = db.GetCollection<UserSession>("user_sessions");
                        return col.Find(s => s.User.Id == userId)
                            .OrderByDescending(s => s.CreatedAt)
                            .ToList();
                    }
                );
            }
            catch (Exception)
            {
                return (List<UserSession>)[];
            }
        }

        /// <summary>
        /// 撤销用户的所有其他会话（除了当前会话）
        /// </summary>
        /// <param name="currentSessionId">当前会话ID</param>
        /// <param name="userId">用户ID</param>
        public static void RevokeOtherUserSessions(string currentSessionId, long userId)
        {
            try
            {
                ExecuteDbOperation(db =>
                {
                    var col = db.GetCollection<UserSession>("user_sessions");

                    var otherSessions = col.Find(s =>
                        s.User.Id == userId
                        && s.SessionId != currentSessionId
                        && s.Status == SessionStatus.Active
                    );

                    foreach (var session in otherSessions)
                    {
                        session.Status = SessionStatus.Revoked;
                        session.UpdatedAt = DateTime.Now;
                        col.Update(session);
                    }

                    return true;
                });
            }
            catch (Exception)
            {
                // 忽略撤销错误
            }
        }

        /// <summary>
        /// 异步撤销用户的所有其他会话（除了当前会话）
        /// </summary>
        /// <param name="currentSessionId">当前会话ID</param>
        /// <param name="userId">用户ID</param>
        public static async Task RevokeOtherUserSessionsAsync(string currentSessionId, long userId)
        {
            try
            {
                await ExecuteDbOperationAsync(
                    "user_sessions",
                    db =>
                    {
                        var col = db.GetCollection<UserSession>("user_sessions");

                        var otherSessions = col.Find(s =>
                            s.User.Id == userId
                            && s.SessionId != currentSessionId
                            && s.Status == SessionStatus.Active
                        );

                        foreach (var session in otherSessions)
                        {
                            session.Status = SessionStatus.Revoked;
                            session.UpdatedAt = DateTime.Now;
                            col.Update(session);
                        }
                    }
                );
            }
            catch (Exception)
            {
                // 忽略撤销错误
            }
        }
        #endregion

        #region Last Login User
        /// <summary>
        /// 保存最后登录用户信息
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        public static void SaveLastLoginUser(UserInfo userInfo)
        {
            try
            {
                ExecuteDbOperation(db =>
                {
                    var col = db.GetCollection<LastLoginInfo>("last_login_info");

                    var lastLoginInfo = new LastLoginInfo
                    {
                        Username = userInfo.Username,
                        DisplayName = userInfo.DisplayName,
                        AvatarUrl = userInfo.AvatarUrl,
                        LastLoginTime = DateTime.Now,
                        UpdatedAt = DateTime.Now,
                    };

                    col.Upsert(lastLoginInfo);
                    return true;
                });
            }
            catch (Exception)
            {
                // 静默失败，不影响主要功能
            }
        }

        /// <summary>
        /// 异步保存最后登录用户信息
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        public static async Task SaveLastLoginUserAsync(UserInfo userInfo)
        {
            try
            {
                await ExecuteDbOperationAsync(
                    "last_login_info",
                    db =>
                    {
                        var col = db.GetCollection<LastLoginInfo>("last_login_info");

                        var lastLoginInfo = new LastLoginInfo
                        {
                            Username = userInfo.Username,
                            DisplayName = userInfo.DisplayName,
                            AvatarUrl = userInfo.AvatarUrl,
                            LastLoginTime = DateTime.Now,
                            UpdatedAt = DateTime.Now,
                        };

                        col.Upsert(lastLoginInfo);
                    }
                );
            }
            catch (Exception)
            {
                // 静默失败，不影响主要功能
            }
        }

        /// <summary>
        /// 获取最后登录用户信息
        /// </summary>
        /// <returns>最后登录用户信息，如果不存在则返回null</returns>
        public static LastLoginInfo? GetLastLoginUserInfo()
        {
            try
            {
                return ExecuteDbOperation(db =>
                {
                    var col = db.GetCollection<LastLoginInfo>("last_login_info");
                    return col.FindById("last_login");
                });
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 异步获取最后登录用户信息
        /// </summary>
        /// <returns>最后登录用户信息，如果不存在则返回null</returns>
        public static async Task<LastLoginInfo?> GetLastLoginUserInfoAsync()
        {
            try
            {
                return await ExecuteDbOperationAsync(
                    "last_login_info",
                    db =>
                    {
                        var col = db.GetCollection<LastLoginInfo>("last_login_info");
                        return col.FindById("last_login");
                    }
                );
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static void SaveLastLoginUser(string username)
        {
            var userInfo = new UserInfo { Username = username };
            SaveLastLoginUser(userInfo);
        }

        public static async Task SaveLastLoginUserAsync(string username)
        {
            var userInfo = new UserInfo { Username = username };
            await SaveLastLoginUserAsync(userInfo);
        }

        public static string? GetLastLoginUser()
        {
            var lastLoginInfo = GetLastLoginUserInfo();
            return lastLoginInfo?.Username;
        }

        public static async Task<string?> GetLastLoginUserAsync()
        {
            var lastLoginInfo = await GetLastLoginUserInfoAsync();
            return lastLoginInfo?.Username;
        }

        public static void ClearLastLoginUser()
        {
            try
            {
                ExecuteDbOperation(db =>
                {
                    var col = db.GetCollection<LastLoginInfo>("last_login_info");
                    return col.Delete("last_login");
                });
            }
            catch (Exception)
            {
                // 静默失败
            }
        }

        public static async Task ClearLastLoginUserAsync()
        {
            try
            {
                await ExecuteDbOperationAsync(
                    "last_login_info",
                    db =>
                    {
                        var col = db.GetCollection<LastLoginInfo>("last_login_info");
                        return col.Delete("last_login");
                    }
                );
            }
            catch (Exception)
            {
                // 静默失败
            }
        }
        #endregion

        #region RecycleBin
        private static void AddToRecycleBin(
            string type,
            string fileName,
            string filePath,
            string message,
            DateTime originalTime,
            string shareCode = ""
        )
        {
            ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<RecycleRecord>("recycle");
                col.Insert(
                    new RecycleRecord
                    {
                        Type = type,
                        FileName = fileName,
                        FilePath = filePath,
                        Message = message,
                        OriginalTime = originalTime,
                        ShareCode = shareCode,
                    }
                );
                return true;
            });
        }

        public static IEnumerable<RecycleRecord> GetRecycleRecords()
        {
            return ExecuteDbOperation(db =>
            {
                var col = db.GetCollection<RecycleRecord>("recycle");
                return col.FindAll().OrderByDescending(r => r.DeletedAt).ToList();
            });
        }

        public static void ClearRecycleBin()
        {
            ExecuteDbOperation(db =>
            {
                db.DropCollection("recycle");
                return true;
            });
        }

        /// <summary>
        /// 获取所有文件的文件名列表，包括上传和下载的文件
        /// </summary>
        /// <returns>文件名列表</returns>
        public static List<string> GetAllFileNames()
        {
            return ExecuteDbOperation(db =>
            {
                var uploadCol = db.GetCollection<UploadRecord>("uploads");
                var downloadCol = db.GetCollection<DownloadRecord>("downloads");

                var uploadFileNames = uploadCol
                    .FindAll()
                    .Select(r => r.FileName)
                    .Where(name => !string.IsNullOrEmpty(name));
                var downloadFileNames = downloadCol
                    .FindAll()
                    .Select(r => r.FileName)
                    .Where(name => !string.IsNullOrEmpty(name));

                return uploadFileNames.Concat(downloadFileNames).ToList();
            });
        }

        /// <summary>
        /// 异步获取所有文件的文件名列表
        /// </summary>
        /// <returns>文件名列表</returns>
        public static async Task<List<string>> GetAllFileNamesAsync()
        {
            return await ExecuteDbOperationAsync(
                "files",
                db =>
                {
                    var uploadCol = db.GetCollection<UploadRecord>("uploads");
                    var downloadCol = db.GetCollection<DownloadRecord>("downloads");

                    var uploadFileNames = uploadCol
                        .FindAll()
                        .Select(r => r.FileName)
                        .Where(name => !string.IsNullOrEmpty(name));
                    var downloadFileNames = downloadCol
                        .FindAll()
                        .Select(r => r.FileName)
                        .Where(name => !string.IsNullOrEmpty(name));

                    return uploadFileNames.Concat(downloadFileNames).ToList();
                }
            );
        }
        #endregion
    }
}
